package main

import (
	"encoding/json"
	"github.com/hpcloud/tail"
	"os"
	"strconv"
	"strings"
	"watchlog-agent/bean"
	"watchlog-agent/core"
	"watchlog-agent/util"
)

func main() {
	/**uuid ip serverName**/
	ip := util.RealIp()
	var logs []bean.AgentInfo
	params := make(map[string]string)
	if len(os.Args) > 1 {
		for _, val := range os.Args {
			if strings.Contains(val, "=") {
				data := strings.Split(val, "=")
				if strings.EqualFold(data[0], "logs") {
					//处理多日志
					err := json.Unmarshal([]byte(data[1]), &logs)
					if err != nil {
						panic(err)
					}
				} else {
					params[data[0]] = data[1]
				}
			}
		}
	}
	//获取系统mac地址
	mac, _ := util.NewMacAddress()
	//对读取的内容进行加密
	macEncrpyt, err := util.Encrypt([]byte(util.Security_Key), []byte(mac.String()))
	if err != nil {
		panic(err)
	}
	agent := bean.Agent{
		//去除uuid的横线
		AgentIp:  ip,
		AgentMac: macEncrpyt,
		LogInfos: logs,
		Type:     1,
		State:    1,
	}
	jsonData, err := json.Marshal(agent)
	if err != nil {
		panic(err)
	}
	port, _ := strconv.Atoi(params["port"])
	client, err := core.NewWebSocketClient(util.ServerRoute(params["ip"], port), true, 5)
	if err != nil {
		util.Log.Fatal("websocket dial error: ", err)
	}
	defer client.Stop()
	go client.Start()
	//发送标识数据
	client.Write(jsonData)
	for i := 0; i < len(logs); i++ {
		go watchLog(agent.AgentMac, logs[i].ServerName, logs[i].LogPath, client)
	}
	//等待线程完成
	select {}

}

// 日志监听
func watchLog(agentMac string, serverName string, logPath string, ws *core.WebSocketClient) {
	// 创建tail实例
	t, err := tail.TailFile(logPath, tail.Config{
		Follow: true,
		ReOpen: true,
		Poll:   true,
		Location: &tail.SeekInfo{
			Offset: 0,
			Whence: 2,
		},
	})
	if err != nil {
		util.Log.Fatal(err)
	}
	// 处理日志
	for line := range t.Lines {
		//util.Log.Info(serverName + " - " + (line.Text))
		//对读取的内容进行加密
		ciphertext, err := util.Encrypt([]byte(util.Security_Key), []byte(line.Text))
		if err != nil {
			panic(err)
		}
		logContent := bean.LogContent{
			AgentMac:   agentMac,
			ServerName: serverName,
			Line:       ciphertext,
			Type:       2,
		}
		jsonData, _ := json.Marshal(logContent)
		ws.Write(jsonData)
	}
}
